// pages/home/order-list/order-item/index.js
import {
  request,
  baseurl
} from '../../../../utils/index.js';
import Notify from '../../../../miniprogram_npm/@vant/weapp/notify/notify.js';
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import { getExtractCode } from "../../../../api/tansfer";
import { deliveryOrder, updateDeliveryTimePre } from "../../../../api/order";
import dayjs from "dayjs";

var amapFile = require('../../../../utils/amap-wx.js');
const recorderManager = wx.getRecorderManager();
const InnerAudioContext = wx.createInnerAudioContext();
InnerAudioContext.autoplay = false;

Component({

  /**
   * 组件的属性列表
   */
  properties: {
    orderData: {
      type: Object,
      value: {}
    },
    index: Number
  },

  /**
   * 组件的初始数据
   */
  data: {
    firstChannelList: ['美团外卖', '美团团购', '饿了么', '抖音'], // 优先渠道
    recording: false, // 录音中
    recordPath: '',
    recordPlaying: false, // 播放中
    codeDialogVisible: false,
    extractCode: '',
    modifyDialogVisible: false,
    timeList: [],
    checkTimeIndex: 0,
  },

  observers: {
    'orderData': function (orderData) {
      if (orderData.recordPath) {
        this.setData({
          recordPath: orderData.recordPath || ''
        })
      }
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 刷新列表
    refreshList() {
      this.triggerEvent('refresh')
    },
    clipboardData(e) {
      wx.setClipboardData({
        data: e.currentTarget.dataset.text,
        success(res) {
          wx.showToast({
            title: "复制成功！"
          })
        },
        fail(e) {
          console.log(e)
        }
      })
    },
    // 跳转详情页
    toDetail: function (e) {
      console.log(e.currentTarget.dataset.item.ordNo, e.currentTarget.dataset)
      const ordNo = e.currentTarget.dataset.item.ordNo
      wx.navigateTo({
        url: `../detail/detail?proid=${ordNo}`
      })
    },
    // 电话拨打
    tels: function (e) {
      console.log(e.currentTarget.dataset.tel)
      wx.makePhoneCall({
        phoneNumber: e.currentTarget.dataset.tel
      })
    },
    openLocation(e) {
      console.log('ditu ', e.currentTarget.dataset.item, e.currentTarget.dataset.item.addressLat)
      // wx.getLocation({
      //   type: 'wgs84',
      //   success: function (res) {
      //     wx.openLocation({ //​使用微信内置地图查看位置。
      //       latitude: Number(e.currentTarget.dataset.item.addressLat), //要去的纬度-地址
      //       longitude: Number(e.currentTarget.dataset.item.addressLng), //要去的经度-地址
      //       name: e.currentTarget.dataset.item.address2,
      //       address: e.currentTarget.dataset.item.address2
      //     })
      //   },
      //   fail: function (error) {
      //     console.log(error)
      //   }
      // })

      wx.openLocation({ //​使用微信内置地图查看位置。
        latitude: Number(e.currentTarget.dataset.item.addressLat), //要去的纬度-地址
        longitude: Number(e.currentTarget.dataset.item.addressLng), //要去的经度-地址
        name: e.currentTarget.dataset.item.address2,
        address: e.currentTarget.dataset.item.address2,
        complete: function () {
          console.log('1')
        },
        fail: function (e) {
          console.log(e)
        }
      })
    },
    // 列表置顶
    Topping(e) {
      let index = e.currentTarget.dataset.index;
      if (index > 0) {
        this.triggerEvent('totop', index)
      }
    },
    /**
     * 列表向上一级
     */
    ColumnUp(e) {
      // console.log('e',e.currentTarget.dataset.item,e.currentTarget.dataset.index)
      let index = e.currentTarget.dataset.index;
      if (index > 0) {
        let busArr = []; //获取数组
        if (e.currentTarget.dataset.status == 6) {
          busArr = this.data.prolist; //获取列表中的所有数组
        } else if (e.currentTarget.dataset.status == 7) {
          busArr = this.data.prolisting; //获取列表中的所有数组
        } else if (e.currentTarget.dataset.status == 8) {
          busArr = this.data.prolisted; //获取列表中的所有数组
        }
        busArr.splice(index, 1, busArr[index - 1]);
        busArr.splice(index - 1, 1, e.currentTarget.dataset.item);
        if (e.currentTarget.dataset.status == 6) {
          this.setData({
            prolist: busArr
          });
        } else if (e.currentTarget.dataset.status == 7) {
          this.setData({
            prolisting: busArr
          });
        } else if (e.currentTarget.dataset.status == 8) {
          this.setData({
            prolisted: busArr
          });
        }
      }
    },
    /**
     * 扫码入库
     */
    scanningWarehousing(e) {
      console.log('e扫描', e.currentTarget.dataset.id, )
      const orderData = e.currentTarget.dataset.item;
      const thisOrderId = orderData.ordNo;
      this.getScancode(thisOrderId)
    },
    /**
     * 扫码
     */
    getScancode: function (thisOrderId) {
      var _this = this;
      // 允许从相机和相册扫码
      wx.scanCode({
        success: (res) => {
          var result = res.result;
          console.log(result)
          try {
            const token = wx.getStorageSync('token');
            const distributorId = wx.getStorageSync('distributorId');
            let orderId = thisOrderId;
            let orderDetailId = null;
            try {
              //兼容条码模式
              var json = JSON.parse(result);
              if (json.orderDetailId) {
                orderDetailId = json.orderDetailId;
              } else {
                orderDetailId = json;
              }
            } catch (e) {
              orderDetailId = result;
            }

            if (token !== '') {
              request({
                url: '/addDeliveryScanLog',
                method: 'GET',
                data: {
                  token,
                  orderId,
                  orderDetailId,
                  distributorId
                },
                header: {
                  'Content-Type': 'application/x-www-form-urlencoded',
                  'token': `${token}`
                }
              }).then(res => {
                console.log(res)
                if (res.data.code == 200) {
                  if (orderId && orderId != res.result.ordNo) {
                    wx.showToast({
                      title: '拿错蛋糕了，请仔细检查',
                      icon: 'error',
                      duration: 2000
                    })
                    return;
                  }
                  wx.showToast({
                    title: '扫描成功',
                    icon: 'success',
                    duration: 2000
                  })
                  this.refreshList();
                } else {
                  Notify({
                    message: `${res.data.msg}`,
                    type: 'danger'
                  })
                }
              })
            }
          } catch (e) {
            //console.error(e)
          }
        },
        fail(e) {
          console.log(e)
        }
      })
    },
    /**
     * 签收订单
     */
    getMessstorageing(e) {
      this.getLocation()
      try {
        const token = wx.getStorageSync('token')
        const longitude = wx.getStorageSync('userLongitude')
        const latitude = wx.getStorageSync('userLatitude')
        const ordNo = e.currentTarget.dataset.item.ordNo
        Dialog.confirm({
          title: '签收订单',
          message: ' ',
          width: '93%',
          messageAlign: 'center',
        }).then(() => {
          request({
            url: '/signOrder',
            method: 'GET',
            data: {
              token,
              ordNo,
              longitude,
              latitude
            },
            header: {
              'content-type': 'application/json',
              'token': `${token}`
            }
          }).then(res => {
            // console.log(res.data.code)
            if (res.data.code == 200) {
              Notify({
                message: '签收成功!',
                type: 'success'
              })
              this.refreshList();
            } else if (res.data.code == -1) {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            } else {
              Notify({
                message: `${res.data.msg}`,
                type: 'danger'
              })
            }
          })
          // on close
        }).catch(() => {
          // on cancel
        });
      } catch (e) {
        console.error(e)
      }
    },
    /**
     * 地图跳转高高德
     */
    getLocation() {
      const _this = this;
      this.getAddress();
    },
    getAddress() {
      var myAmapFun = new amapFile.AMapWX({
        key: 'd5e940ac71e33d85ec6ebad1c485e99e'
      });
      myAmapFun.getRegeo({
        success: (res) => {
          wx.setStorageSync('userLongitude', res[0].longitude)
          wx.setStorageSync('userLatitude', res[0].latitude)
        }
      })
    },

    // 开始录音
    startrecord: function (event) {
      const token = wx.getStorageSync('token');
      const {recording} = this.data
      if (recording) {
        return false;
      }
      this.setData({recording: true})

      recorderManager.onStart(() => {

      })
      // 监听录音停止
      recorderManager.onStop((res) => {
        let that = this;
        wx.showLoading({
          title: '上传录音中',
        })
        wx.uploadFile({
          url: '/uploadRecord', //仅为示例，非真实的接口地址
          filePath: res.tempFilePath,
          name: 'file',
          header: {
            'content-type': 'application/json', // 默认值
            'token': `${token}`
          },
          formData: {
            'order_no': event.target.dataset.item.xmbzNo
          },
          success(resfile) {
            wx.hideLoading();
            resfile = JSON.parse(resfile.data);

            that.setData({
              recording: false,
              recordPath: "https://audio.cdn.xiongmaodangao.com/" + resfile.key
            })
          },
          fail(res) {
            wx.hideLoading();
            that.setData({
              recording: false
            })
            console.log(res)
            Notify({
              message: '录音失败',
              type: 'danger'
            })
          }
        })
      })

      recorderManager.onPause(function () {})
      // 监听录音中断
      recorderManager.onInterruptionBegin(function () {})
      // 监听录音中断结束
      recorderManager.onInterruptionEnd(function () {
        onsole.log("录音中断结束")
        recorderManager.resume()
      })

      recorderManager.start({
        duration: 600000,
        format: "mp3",
      })
    },

    // 停止录音
    stoprecord: function (event) {
      recorderManager.stop();
    },

    // 播放录音
    playrecord: function (event) {
      this.setData({recordPlaying: true})
      let that = this;
      InnerAudioContext.onEnded(function () {
        console.log("播放结束")
        this.setData({recordPlaying: false})
      });
      InnerAudioContext.src = event.target.dataset.recordpath
      InnerAudioContext.play()
    },
    // 暂停播放
    pauserecord: function (event) {
      InnerAudioContext.pause();
      this.setData({
        recordPlaying: false,
      })
    },

    // 提取码
    openCodeDialog: function () {
      this.setData({codeDialogVisible: true, extractCode: ''})
    },
    handleCodeCancel: function () {
      this.setData({codeDialogVisible: false})
    },
    handleCodeConfirm: async function () {
      const token = wx.getStorageSync('token');
      const distributorId = wx.getStorageSync('distributorId');
      const {extractCode, orderData} = this.data
      const codeRes = await getExtractCode({code: extractCode})
      const data = codeRes.data && codeRes.data.result

      if (!data || !data.orderDetailId) {
        Notify({
          message: codeRes.data.msg || '提取码解析失败，请重试',
          type: 'danger'
        })
        return
      }

      request({
        url: '/addDeliveryScanLog',
        method: 'GET',
        data: {
          token,
          orderId: orderData.ordNo,
          orderDetailId: data.orderDetailId,
          distributorId
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'token': `${token}`
        }
      }).then(res => {
        console.log(res)
        if (res.data.code == 200) {
          if (orderData.ordNo && orderData.ordNo != res.data.result.ordNo) {
            wx.showToast({
              title: '拿错蛋糕了，请仔细检查',
              icon: 'error',
              duration: 2000
            })
            return;
          }
          wx.showToast({
            title: '提取成功',
            icon: 'success',
            duration: 2000
          })
          this.setData({codeDialogVisible: false})
          this.refreshList();
        } else {
          wx.showToast({
            title: `${res.data.msg}`,
            icon: 'error',
          })
        }
      })
    },
    // 异常配送
    abnormalDeliverlying(e) {
      const {ordNo, cityName, xmbzNo} = e.currentTarget.dataset.item
      wx.navigateTo({
        url: `../abnoquery/abnoquery?proid=${ordNo}&&city=${cityName}&&xmbzNo=${xmbzNo}`
      })
    },
    // 立即配送
    storageing(e) {
      const ordNo = e.currentTarget.dataset.item.ordNo
      deliveryOrder({ordNo}).then(res => {
        if(res.data.code == 200) {
          wx.showToast({
            title: '配送成功',
            icon: 'success',
            duration: 2000
          })
          this.refreshList();
        } else {
          Notify({
            message: `${res.data.msg}`,
            type: 'danger'
          })
        }
      })
    },
    // 配送修改
    openModifyDialog() {
      let start = dayjs().format('HH')
      const timeList = [];
      for(let i = Number(start) + 1; i < 24; i++){
        timeList.push({startTime: i, endTime: i + 1})
      }

      this.setData({modifyDialogVisible: true, timeList, checkTimeIndex: 0})
    },
    handleModifyCancel() {
      this.setData({modifyDialogVisible: false})
    },
    handleModifyConfirm() {
      const {orderData, checkTimeIndex} = this.data
      const time = this.data.timeList[checkTimeIndex]
      const dateStr = dayjs().format('YYYY-MM-DD')
      if (time) {
        updateDeliveryTimePre({
          ordNo: orderData.ordNo,
          startTime: `${dateStr} ${time.startTime}:00:00`,
          endTime: `${dateStr} ${time.startTime == 23 ? '23:59:59': `${time.endTime}:00:00`}`,
        }).then(res => {
          if (res.data.code === 200) {
            Notify({
              message: '修改成功！!',
              type: 'success'
            })
            this.setData({modifyDialogVisible: false})
            this.refreshList()
          }
        })
      } else {
        wx.showToast({
          title: '请选择时间',
          icon: 'error',
          duration: 2000
        })
      }
    },
    checkModifyTime(e) {
      const index = e.currentTarget.dataset.index
      this.setData({checkTimeIndex: index})
    },
    // 修改订单
    modifyOrder(e) {
      const {item} = e.currentTarget.dataset
      wx.navigateTo({
        url: '/pages/order/modify-order/index',
        success:(res)=>{
          // 发送一个事件
				  res.eventChannel.emit('modify-order',{ orderData: item })
        }
      })
    }
  }
})